<template>
  <div style="padding: 10px;">
    <el-row>
      <el-col :span="24">
        <div style="display: flex;">

          <div>
            <!--            <el-button type="primary">查询</el-button>-->
            <el-form :model="list_params" ref="searchForm"  size="small" :inline="true" @submit.native.prevent="() => handleQuery()">
              <el-form-item label="" label-width="80px" prop="returnWaybillNumber">
                <el-input v-model="list_params.returnWaybillNumber" placeholder="搜索运单号" ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"  size="mini" native-type="submit">搜索</el-button>
                <el-button  size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div style="flex: 1;"></div>
          <div>
            <!--            <el-button>删除</el-button>-->
<!--            <el-button @click="handleEnable(1)" >禁用</el-button>-->
<!--            <el-button @click="handleEnable(0)" >启用</el-button>-->
            <!-- <el-button @click="handleExport">导出</el-button>
            <el-button>导入</el-button> -->
            <el-button type="primary" @click="addOrder" >新增</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="24">
        <el-table :data="list_data" >
          <el-table-column label="退运单号" prop="returnWaybillNumber"></el-table-column>
          <el-table-column label="供货单" prop="supplyListId">

          </el-table-column>
          <el-table-column label="合同号" prop="supplyListId">
            <template slot-scope="scope" >
            {{ scope.row.supplyList.contractNumber }}
            </template>
          </el-table-column>
          <el-table-column label="货柜号" prop="supplyListId">
            <template slot-scope="scope" >
              {{ scope.row.supplyList.containerNumber }}
            </template>
          </el-table-column>
          <el-table-column label="货主">
            <template slot-scope="scope" >
              {{ scope.row.supplyList.cargoOwnerName }}
            </template>
          </el-table-column>
          <el-table-column label="供货产品">
            <template slot-scope="scope" >
              {{ scope.row.supplyList.productNames }}
            </template>
          </el-table-column>
          <el-table-column label="退运日期" prop="returnedDate"></el-table-column>
          <el-table-column label="总数量" prop=""></el-table-column>
          <el-table-column label="合计退运金额" prop="totalAmt"></el-table-column>
          <el-table-column label="状态" prop="enable">
            <template slot-scope="scope" >
              {{ scope.row.enable==1?'已退运':'已撤销'}}
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="op">
            <template slot-scope="scope" >
              <el-button type="text" @click="showInfo(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <el-drawer title="新增退运单"
               size="80%"
               :visible.sync="add_dialog_show">
      <el-form inline :model="form_data" :rules="form_data_rules" ref="form" >
        <div class="section">
          <el-row>
            <el-col :span="6">
              <el-form-item prop="supplyListId" label="供货单">
                <el-select filterable  v-model="form_data.supplyListId" size="width:100%;" @change="onSupplyOrderChange">
                  <el-option v-for="item in supply_order_list" :label="item.contractNumber +' - '+item.containerNumber +' - '+item.cargoOwnerName" :value="item.id" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="returnWaybillNumber" label="退运单号">
                <el-input v-model="form_data.returnWaybillNumber"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="returnedDate" label="退运日期">
                <el-date-picker v-model="form_data.returnedDate" size="width:100%;"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col>
              <div style="padding-top: 12px;">
                <el-table :data="supply_order_info?[supply_order_info]:[]">
                  <el-table-column label="合同号" prop="contractNumber" ></el-table-column>
                  <el-table-column label="货柜号" prop="containerNumber" ></el-table-column>
                  <el-table-column label="货主" prop="cargoOwnerName" ></el-table-column>
                  <el-table-column label="供货产品" prop="productNames" ></el-table-column>
                  <el-table-column label="总数量" prop="totalQty" ></el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="section">
          <div class="section-title">
            海运费用
          </div>
          <div style="margin-top: 10px;">
            <el-table :data="sea_fee_list" show-summary  :summary-method="getSummaries" >
              <el-table-column label="序号" prop="index">
                <template slot-scope="scope" >
                  <span>{{scope.$index+1}}</span>
                </template>
              </el-table-column>
              <el-table-column label="科目" prop="financeSubjectName">
              </el-table-column>
              <el-table-column label="金额" prop="amt">
              </el-table-column>
              <el-table-column label="备注" prop="remark">
                <template slot-scope="scope" >
                  {{scope.row.remark == ''?'-':scope.row.remark}}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="section">
          <div class="section-title">
            清关费用
          </div>
          <div>
            <el-table :data="clearance_fee_list" show-summary  :summary-method="getSummaries" >
              <el-table-column label="序号" prop="index">
                <template slot-scope="scope" >
                  <span>{{scope.$index+1}}</span>
                </template>
              </el-table-column>
              <el-table-column label="科目" prop="financeSubjectName">
              </el-table-column>
              <el-table-column label="金额" prop="amt">
              </el-table-column>
              <el-table-column label="备注" prop="remark">
                <template slot-scope="scope" >
                  {{scope.row.remark == ''?'-':scope.row.remark}}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div class="section">
          <div>
            <el-form-item label="本次退运金额：" prop="">
              <el-input v-model="form_data.amt" type="number"></el-input>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="本次退运金额：">
              {{getSum()}}
            </el-form-item>
          </div>
          <div  class="custom-form-item">
            <el-row>
              <el-col :span="2">
                <div style="line-height: 32px;font-size: 14px;font-weight: 700;color: #606266;">单据备注：</div>
              </el-col>
              <el-col :span="22">
                <el-form-item style="width: 100%;" label="" prop="remark" >
                  <el-input v-model="form_data.remark" placeholder="请输入" style="width: 100%;"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

          </div>
        </div>

        <div class="section">
          <el-row>
            <el-col :span="12">
              <div>
                <div style="padding-bottom: 12px;">图片附件</div>
                <div>

                  <el-form-item prop="pictures" label-width="0px" >
                    <el-upload ref="field101" :file-list="pictures" :action="uploadImgUrl" :limit="10" multiple
                               :headers="headers" :on-success="field101Success" :on-remove="field101Remove"
                               :before-upload="field101BeforeUpload" list-type="picture-card" accept="image/*">
                      <i class="el-icon-plus"></i>
                    </el-upload>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div>
                <div style="padding-bottom: 12px;">文件附件</div>
                <div>

                  <el-form-item prop="pictures" label-width="0px" >
                    <el-upload ref="field102" :file-list="files" :action="uploadImgUrl" :limit="10" multiple
                               :headers="headers" :on-success="field102Success" :on-remove="field102Remove"
                               :before-upload="field101BeforeUpload"  >
                      <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                  </el-form-item>
                </div>
              </div>
            </el-col>
          </el-row>

        </div>
        <div class="section" style="display: flex;justify-content: flex-end;position: sticky;bottom: 0px;">
          <el-button type="primary" @click="submitData">提交</el-button>
        </div>
      </el-form>
    </el-drawer>
    <el-drawer title="退运单详情"
               size="80%"
               :visible.sync="dialog_show">
      <el-form inline>
        <div class="section">
          <el-row>
            <el-col :span="6">
              <el-form-item prop="supplyListId" label="供货单">
                {{form_data.supplyListId}}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="returnWaybillNumber" label="退运单号">
                {{form_data.returnWaybillNumber}}
              </el-form-item>
            </el-col>
            <el-col :span="6">
<!--              <el-form-item prop="returnedDate" label="退运日期">-->
<!--                {{form_data.returnedDate}}-->
<!--              </el-form-item>-->

              <el-form-item prop="enable" label="状态">
                {{form_data.enable?'已退运':'已撤销'}}
              </el-form-item>
            </el-col>
            <el-col>
              <div style="padding-top: 12px;">
                <el-table :data="[supply_order_info]">
                  <el-table-column label="合同号" prop="contractNumber" ></el-table-column>
                  <el-table-column label="货柜号" prop="containerNumber" ></el-table-column>
                  <el-table-column label="货主" prop="cargoOwnerName" ></el-table-column>
                  <el-table-column label="供货产品" prop="productNames" ></el-table-column>
                  <el-table-column label="总数量" prop="totalQty" ></el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="section">
          <div class="section-title">
            海运费用
          </div>
          <div>
            <el-table :data="sea_fee_list" show-summary>
              <el-table-column label="序号" prop="index">
                <template slot-scope="scope" >
                  <span>{{scope.$index+1}}</span>
                </template>
              </el-table-column>
              <el-table-column label="科目" prop="financeSubjectName">
              </el-table-column>
              <el-table-column label="金额" prop="amt">
              </el-table-column>
              <el-table-column label="备注" prop="remark">
                <template slot-scope="scope" >
                  {{scope.row.remark == ''?'-':scope.row.remark}}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="section">
          <div class="section-title">
            清关费用
          </div>
          <div>
            <el-table :data="clearance_fee_list" show-summary  >
              <el-table-column label="序号" prop="index">
                <template slot-scope="scope" >
                  <span>{{scope.$index+1}}</span>
                </template>
              </el-table-column>
              <el-table-column label="科目" prop="financeSubjectName">
              </el-table-column>
              <el-table-column label="金额" prop="amt">
              </el-table-column>
              <el-table-column label="备注" prop="remark">
                <template slot-scope="scope" >
                  {{scope.row.remark == ''?'-':scope.row.remark}}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div class="section">
          <el-row>
            <el-col :span="12">
              <div>图片附件</div>
              <div>
                <el-row :gutter="10">
                  <el-col v-for="item in imgs" :span="4" >
                    <el-image
                      style="width: 100%; height: 100px;"
                      :src="item.url"
                    >        </el-image>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="12">
              <div>文件附件</div>
              <div>
                <div v-for="item in docs" style="background: #F3F4F6;padding: 16px;border-radius: 16px;margin: 10px 0px;display: flex;">
                  <div style="flex: 1;">
                    {{item.name}}
                  </div>
                  <div style="margin: 0px 10px;cursor: pointer;" @click="openNav(item.url)" ><i class="el-icon-view"></i></div>
                  <div style="margin: 0px 10px;cursor: pointer;" @click="openNav(item.url)"  ><i class="el-icon-download"></i></div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="section">
<!--          <div>-->
<!--            <el-form-item label="本次退运金额：">-->
<!--              <el-input v-model="form_data.amt"></el-input>-->
<!--            </el-form-item>-->
<!--          </div>-->
          <div>
            <el-form-item label="本次退运金额：">
              {{form_data.amt}}
            </el-form-item>
          </div>
          <div>
            <el-form-item label="单据备注：">
              {{form_data.remark}}
<!--              <el-input v-model="form_data.remark"></el-input>-->
            </el-form-item>
          </div>
        </div>
        <div class="section" style="display: flex;justify-content: flex-end;position: sticky;bottom: 0px;">
          <el-button type="primary" @click="dialog_show=false;add_dialog_show=true;">编辑</el-button>
        </div>

      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { list,add,detail,update } from "@/api/supply/return";
import { list as supplyOrderList,detail as supplyOrderDetail } from "@/api/supply/order";
import { list as feeList} from "@/api/fee/fee";
import { list as clearList } from "@/api/clearance/order";
import { list as seaList } from "@/api/logistics/sea";
import { getToken } from "@/utils/auth";
import { getUploadFiles,getUploadFileUrls } from '@/api/common'
export default {
  name: "return",
  data() {
    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      pictures:[],
      files:[],
      imgs:[],
      docs:[],
      table_height:window.innerHeight - 300,
      list_params:{},
      form_data:{},
      list_data:[],
      form_data_rules:{
        supplyListId:[{required:true,message:'请选择供货单',trigger:'change'}],
        returnWaybillNumber:[{required:true,message:'请填写退运单号',trigger:'blur'}]
      },
      add_dialog_show:false,
      dialog_show:false,
      supply_order_list:[],
      supply_order_info:{},
      //清关费用列表
      clearance_fee_list:[],
      //海运费用列表
      sea_fee_list:[],
    }
  },
  created() {
    this.getList()
    this.getSupplyOrderList()
  },
  methods: {
    getSupplyOrderList(){
      supplyOrderList({supplyListStatusList:'4,5,6',is_page:0}).then(res=>{
        this.supply_order_list = res.rows
      })
    },
    getList(){
      list(this.list_params).then(res=>{
        this.list_data = res.rows
      })
    },
    handleQuery(){
      this.getList()
    },
    resetQuery(){
      this.list_params = {}
      this.getList()
    },
    showInfo({id}){
      this.dialog_show = true;
      this.sea_fee_list = [];
      this.clearance_fee_list = []
      detail(id).then((res1)=>{
        console.log(res1)
        this.form_data = res1.data
        supplyOrderDetail(this.form_data.supplyListId).then(res=>{
          this.supply_order_info = res.data
        })
        feeList({supplyListId:this.form_data.supplyListId,bizType:1,is_page:0}).then(res=>{
          let sea_fee_list = this.sea_fee_list;
          sea_fee_list = sea_fee_list.concat(res.rows)
          this.sea_fee_list = sea_fee_list;
        })

        seaList({supplyListId:this.form_data.supplyListId,is_page:0}).then((res)=>{
          let sea_fee_list = this.sea_fee_list;
          if(res.rows.length != 0){
            let item = res.rows[0];
            sea_fee_list = sea_fee_list.concat({
              financeSubjectName:'海运费成本',
              amt:item.oceanFreightCostRmb?item.oceanFreightCostRmb:'-'
            },{
              financeSubjectName:'单证费实付',
              amt:item.docFeeActPaidRmb?item.item.docFeeActPaidRmb:'-'
            })
          }
          this.sea_fee_list = sea_fee_list;
        })
        clearList({supplyListId:this.form_data.supplyListId,is_page:0}).then((res)=>{
          let clearance_fee_list = this.clearance_fee_list;
          if(res.rows.length != 0){
            let item = res.rows[0];
            clearance_fee_list = clearance_fee_list.concat({
              financeSubjectName:'实际运输费',
              amt:item.actualTransportFee?item.actualTransportFee:'-'
            },{
              financeSubjectName:'实际进口税金',
              amt:item.actualImportTax?item.item.actualImportTax:'-'
            },{
              financeSubjectName:'实际清关费',
              amt:item.actualCustomsClearanceFee?item.item.actualCustomsClearanceFee:'-'
            })
          }
          this.clearance_fee_list = clearance_fee_list;
        })
        feeList({supplyListId:this.form_data.supplyListId,bizType:4,is_page:0}).then(res=>{
          let clearance_fee_list = this.clearance_fee_list;
          clearance_fee_list = clearance_fee_list.concat(res.rows);
          this.clearance_fee_list = clearance_fee_list
        })


        let imgs = res1.data.imgFiles;
        let docs = res1.data.docFiles;
        console.log(imgs)
        if (imgs != ''){
          getUploadFiles(imgs).then((img_res)=>{
            this.imgs = getUploadFileUrls(img_res.data);
          })
        }
        if (docs != ''){
          getUploadFiles(docs).then((img_res)=>{
            this.docs = getUploadFileUrls(img_res.data);
          })
        }
      })
      // this.form_data = row

    },
    addOrder(){
      this.form_data = {}
      this.supply_order_info = undefined
      this.sea_fee_list = []
      this.clearance_fee_list = []
      this.add_dialog_show = true;
      this.getSupplyOrderList()
    },
    onSupplyOrderChange(e){
      this.sea_fee_list = [];
      this.clearance_fee_list = [];
      supplyOrderDetail(e).then(res=>{
        this.supply_order_info = res.data
      })
      feeList({supplyListId:e,bizType:1,is_page:0}).then(res=>{
        let sea_fee_list = this.sea_fee_list;
        sea_fee_list = sea_fee_list.concat(res.rows)
        this.sea_fee_list = sea_fee_list;
      })

      seaList({supplyListId:this.form_data.supplyListId,is_page:0}).then((res)=>{
        let sea_fee_list = this.sea_fee_list;
        if(res.rows.length != 0){
          let item = res.rows[0];
          sea_fee_list = sea_fee_list.concat({
            financeSubjectName:'海运费成本',
            amt:item.oceanFreightCostRmb?item.oceanFreightCostRmb:'-'
          },{
            financeSubjectName:'单证费实付',
            amt:item.docFeeActPaidRmb?item.item.docFeeActPaidRmb:'-'
          })
        }
        this.sea_fee_list = sea_fee_list;
      })
      clearList({supplyListId:this.form_data.supplyListId,is_page:0}).then((res)=>{
        let clearance_fee_list = this.clearance_fee_list;
        if(res.rows.length != 0){
          let item = res.rows[0];
          clearance_fee_list = clearance_fee_list.concat({
            financeSubjectName:'实际运输费',
            amt:item.actualTransportFee?item.actualTransportFee:'-'
          },{
            financeSubjectName:'实际进口税金',
            amt:item.actualImportTax?item.item.actualImportTax:'-'
          },{
            financeSubjectName:'实际清关费',
            amt:item.actualCustomsClearanceFee?item.item.actualCustomsClearanceFee:'-'
          })
        }
        this.clearance_fee_list = clearance_fee_list;
      })
      feeList({supplyListId:e,bizType:4,is_page:0}).then(res=>{
        let clearance_fee_list = this.clearance_fee_list;
        clearance_fee_list = clearance_fee_list.concat(res.rows);
        this.clearance_fee_list = clearance_fee_list
      })
    },
    submitData(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          let form_data = {
            ...this.form_data,
            totalAmt:this.form_data.amt
          }
          if (this.form_data.id){
            update(form_data).then(res=>{
              this.$message.success('修改成功')
              this.add_dialog_show = false
              this.getList()
            });
            }
          else{

            add(form_data).then(res=>{
              this.$message.success('添加成功')
              this.add_dialog_show = false
              this.getList()
            })
          }

        } else {
          return false;
          }
      });
    },

    getSummary(params){
      const { columns, data } = params;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计：'; // 首列添加自定义合计文字
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if ((column.property=="amt" ) && !values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) { // 若不能转成数字就不进行累加
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    field101BeforeUpload(file) {
      const postfix= file.name.substring(file.name.lastIndexOf('.')+1)
      if(!this.fileSuffix.includes(postfix)){
        this.$message.error('文件类型仅支持'+this.fileSuffix);
        return false
      }
      console.log(postfix)
    },
    field101Success(e){
      console.log('field101Success')
      console.log(e)
      let imgFiles = this.form_data.imgFiles?this.form_data.imgFiles:'';
      console.log(imgFiles)
      let imgs = imgFiles == ''?[]:imgFiles.split(',');
      imgs.push(e.data.id)
      this.form_data = {
        ...this.form_data,
        imgFiles:imgs.join(',')
      }
      console.log(this.form_data)
    },
    field101Remove(file, fileList){
      let ids = []
      fileList.forEach((item)=>{
        if (item.id){
          ids.push(item.id);
        }else{
          ids.push(item.response.data.id)
        }
      })
      this.form_data = {
        ...this.form_data,
        imgFiles:ids.join(','),
      }
    },
    field102BeforeUpload(file) {
    },
    field102Success(e){
      console.log(e)
      let docFiles = this.form_data.docFiles?this.form_data.docFiles:'';
      let docs = docFiles == ''?[]:docFiles.split(',');
      docs.push(e.data.id)
      this.form_data = {
        ...this.form_data,
        docFiles:docs.join(',')
      }
    },
    field102Remove(file, fileList){
      let ids = []
      fileList.forEach((item)=>{
        if (item.id){
          ids.push(item.id);
        }else{
          ids.push(item.response.data.id)
        }
      })
      this.form_data = {
        ...this.form_data,
        docFiles:ids.join(','),
      }
    },
    openNav(url){
      window.open(url)
    },
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]));
        if (index === 0) {
          sums[index] = '合计';
          return;
        } else if (index === 2){
          sums[index] = values.reduce((prev, curr) => {
            // console.log(values);
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
    getSum(){
      let sum = 0;
      this.clearance_fee_list.forEach((item)=>{
        if (!isNaN(item.amt)){
          sum+=parseFloat(item.amt);
        }
      })
      this.sea_fee_list.forEach((item)=>{
        if (!isNaN(item.amt)){
          sum+=parseFloat(item.amt);
        }
      })
      this.$set(this.form_data,'amt',sum)
      return sum;
    }
  }
}
</script>

<style scoped>
.section{
  background: #fff;
  padding: 24px;
//padding-bottom: 6px;
  margin: 20px;
  border-radius: 8px;
}
.section-item{
  margin: 10px 0px;
  height: 52px;
}
.section-item-title{
  padding-bottom: 10px;
  font-size: 14px;
}
</style>

<style>

 .el-drawer__body{
   background: #F3F4F6;
 }
.select-custom-icon .el-input__suffix {
  display: none; /* 隐藏默认的下拉箭头 */
}
.select-custom-icon .el-input__suffix::after {
  content: url('../../../assets/icons/more.png'); /* 替换为您的自定义图标路径 */
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}
.popper-class{
  display: none;
}

 .custom-form-item .el-form-item__content{
   display: block;
 }
</style>
